package com.sky.sd.oauth.controller;

import com.sky.sd.common.web.response.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/6/28 16:28
 * <br/>修改日期: 2020/6/28 16:28
 * <br/>修改列表:
 */
@RestController
@RequestMapping("oauth")
public class OauthController {

    @Autowired
    private ConsumerTokenServices tokenServices;

    @GetMapping("/authentication")
    public Authentication userMe() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth;
    }

    @PostMapping("/logout")
    public Result logout(@RequestParam(required = false, value = "access_token") String accessToken, @RequestHeader(required = false, value = "Authorization") String token) {
        if(StringUtils.isBlank(accessToken)) {
            if (StringUtils.isNoneBlank(token)) {
                accessToken = token.substring(OAuth2AccessToken.BEARER_TYPE.length() + 1);
                tokenServices.revokeToken(accessToken);
                SecurityContextHolder.clearContext();
            }
        }
        return Result.success();
    }

    @GetMapping("/hello")
    public Result hello() {
        return Result.success();
    }
}
